﻿using log4net.Core;
using log4net.Layout.Pattern;
using System.IO;
using System.Reflection;

namespace MiniFox.Log
{
    /// <summary>
    /// 
    /// </summary>
    public class LogPatternConverter : PatternLayoutConverter
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="loggingEvent"></param>
        protected override void Convert(TextWriter writer, LoggingEvent loggingEvent)
        {
            if (this.Option != null)
            {
                WriteObject(writer, loggingEvent.Repository, LookupProperty(Option, loggingEvent));
            }
            else
            {
                WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties());
            }
        }
        /// <summary>
        /// 通过反射获取传入的日志对象的某个属性的值  
        /// </summary>
        /// <param name="property"></param>
        /// <param name="loggingEvent"></param>
        /// <returns></returns>
        private object LookupProperty(string property, LoggingEvent loggingEvent)
        {
            object propertyValue = string.Empty;
            var messageObject = loggingEvent.MessageObject;
            if (messageObject == null)
                return propertyValue;
            PropertyInfo propertyInfo = messageObject.GetType().GetProperty(property);
            if (propertyInfo == null)
                return propertyValue;
            propertyValue = propertyInfo.GetValue(loggingEvent.MessageObject);
            return propertyValue;
        }
    }

}
